package com.igeek.d0611.test1;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author: zhiyu
 * @Date:17:32
 * @DESC:
 */
public class T_callable {
    public static void main(String[] args) {
        System.out.println("===============================================");
        CallableDemo callableDemo = new CallableDemo();
        FutureTask<String> task1 = new FutureTask<String>(callableDemo);
        Thread thread = new Thread(task1,"线程");
        thread.start();
        try {
            System.out.println("task1.get() = " + task1.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println("===================匿名内部类====================");
        new Thread(new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                int sum = 0;
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName()+":i="+i);
                    sum+=i;
                }
                return Thread.currentThread().getName() + ",sum=" + sum;
            }
        }),"线程1").start();
        System.out.println("====================lambda===================");
        new Thread(new FutureTask<String>(()->{
                int sum = 0;
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName()+":i="+i);
                    sum+=i;
                }
                return Thread.currentThread().getName() + ",sum=" + sum;
        }),"线程2").start();
        System.out.println("====================标准===================");
        FutureTask<String> task = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                int sum = 0;
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName() + ":i=" + i);
                    sum += i;
                }
                return Thread.currentThread().getName() + ",sum=" + sum;
            }
        });
        new Thread(task,"线程3").start();
        String result = null;
        try {
            result = task.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println("result = " + result);
    }
}
class CallableDemo implements Callable {

    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+":i="+i);
            sum+=i;
        }
        return Thread.currentThread().getName() + ",sum=" + sum;
    }
}
